<template>
  <div class="activity-detail">
    <!-- 添加顶部导航栏 -->
    <div class="top-bar">
      <div class="left-aligned-header-items">
        <div class="header-logo" @click="goToMainHome">
          <img src="../assets/logo.png" alt="Logo" class="logo">
          <span class="logo-text">小白盒</span>
        </div>
        <TopBarSearch />
      </div>
      <div class="user-profile">
        <img :src="currentUser.avatar" alt="用户头像" class="user-avatar" @click="toggleUserOptionsModal">
        <span class="username" @click="toggleUserOptionsModal" style="cursor: pointer;">{{ currentUser.nickname }}</span>
        <span class="message-icon" @click="goToMessageHome"></span>
      </div>
    </div>

    <!-- 用户选项弹窗 -->
    <div v-if="showUserOptionsModal" class="user-options-modal-overlay" @click="closeUserOptionsModal">
      <div class="user-options-modal" @click.stop>
        <div class="user-option" @click="goToPersonalHome">
          <span class="option-icon">👤</span>
          <span class="option-text">个人主页</span>
        </div>
        <div class="user-option" @click="logout">
          <span class="option-icon">🚪</span>
          <span class="option-text">退出登录</span>
        </div>
      </div>
    </div>

    <el-dialog
        v-model="showLoginModal"
        width="320px"
        :show-close="false"
        center
        custom-class="login-required-modal"
    >
      <div style="text-align:center;font-size:20px;font-weight:bold;margin-bottom:20px;">该功能需要登录</div>
      <div style="display:flex;gap:16px;justify-content:center;">
        <el-button @click="showLoginModal = false" style="width:100px;">取消</el-button>
        <el-button type="primary" @click="goToLogin" style="width:100px;background:linear-gradient(90deg,#23272b,#43484d);border:none;">去登录</el-button>
      </div>
    </el-dialog>

    <div class="content-wrapper">
      <!-- 动态内容展示 -->
      <div class="activity-card">
        <div class="activity-header">
          <img class="avatar" :src="userInfo.avatar" @click="goToUserProfile" style="cursor: pointer;" />
          <span class="nickname" @click="goToUserProfile" style="cursor: pointer;">{{ userInfo.nickname }}</span>
        </div>

        <div class="activity-main">
          <div class="activity-content-block">
            <div v-if="topicContent" class="activity-topic">
              <span class="topic-hash">#</span>
              <span class="topic-text">{{ topicContent }}</span>
            </div>
            <div class="activity-content" v-html="formatContent(activity.content)"></div>
          </div>
        </div>

        <div class="activity-images" v-if="activity.mediaUrls && parseImages(activity.mediaUrls).length">
          <template v-for="(media, idx) in parseImages(activity.mediaUrls)" :key="idx">
            <img
                v-if="/\.(jpg|jpeg|png|gif|webp)$/i.test(media)"
                :src="media"
                class="activity-img"
                @click="openMediaViewer(idx)"
                @error="handleImageError"
            />
            <video
                v-else
                :src="media"
                class="activity-img"
                muted
                preload="metadata"
                playsinline
                @click="openMediaViewer(idx)"
            ></video>
          </template>
        </div>
      </div>

      <!-- 评论区域 -->
      <CommentSection :activity-id="activityId" />

      <!-- 媒体查看器组件 -->
      <MediaViewer
          v-if="showViewer"
          :mediaList="mediaList"
          :initialIndex="currentIndex"
          @close="showViewer = false"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import CommentSection from './CommentSection.vue';
import MediaViewer from './MediaViewer.vue';
import TopBarSearch from '../components/TopBarSearch.vue';
import { currentUser } from '../user';

const router = useRouter();
const route = useRoute();
const activityId = route.params.id;
const activity = ref({});
const userInfo = ref({
  nickname: '匿名用户',
  avatar: 'https://example.com/avatars/guest1.jpg'
});
const topicContent = ref('');
const mediaList = ref([]);
const showViewer = ref(false);
const currentIndex = ref(0);
const showLoginModal = ref(false);
const showUserOptionsModal = ref(false);

// 加载动态详情
async function fetchActivity() {
  try {
    const response = await axios.get(`/activity/${activityId}`);

    // 检查响应内容类型
    if (response.headers['content-type'].includes('application/json')) {
      activity.value = response.data;
    } else {
      console.error('Unexpected response type:', response.headers['content-type']);
    }

    // 加载用户信息
    if (activity.value.userId) {
      try {
        const userRes = await axios.get(`/api/user/${activity.value.userId}`);
        userInfo.value.nickname = userRes.data.nickname || '匿名用户';
        userInfo.value.avatar = userRes.data.avatar || 'https://example.com/avatars/guest1.jpg';
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    }

    // 加载话题内容
    try {
      const topicRes = await axios.get(`/activity/${activityId}/topic`);
      topicContent.value = topicRes.data.content || '';
    } catch (error) {
      console.error('获取话题内容失败:', error);
    }
  } catch (error) {
    console.error('加载动态详情失败:', error);
  }
}

// 解析媒体URL，增强容错性
function parseImages(mediaUrls) {
  if (!mediaUrls) return [];
  try {
    const arr = Array.isArray(mediaUrls) ? mediaUrls : JSON.parse(mediaUrls);
    return arr.map(item => {
      if (typeof item === 'string') return item;
      if (item && item.url) return item.url;
      return '';
    }).filter(Boolean);
  } catch (e) {
    console.warn('Failed to parse media URLs:', e);
    return [];
  }
}

// 格式化内容（处理换行）
function formatContent(content) {
  if (!content) return '';
  return content.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>');
}

// 打开媒体查看器
function openMediaViewer(index) {
  const images = parseImages(activity.value.mediaUrls);
  console.log('Parsed media URLs:', images);
  if (images.length === 0) {
    alert('没有可用的媒体资源');
    return;
  }
  mediaList.value = images;
  currentIndex.value = index;
  showViewer.value = true;
}

// 处理图片错误
function handleImageError(event) {
  event.target.src = 'https://example.com/default-image.png';
}

onMounted(async () => {
  await fetchActivity();
  nextTick(() => {
    console.log('All data loaded, rendering images...');
  });
});

// 跳转到用户主页
function goToUserProfile() {
  if (activity.value.userId) {
    router.push(`/user/${activity.value.userId}`);
  }
}

// 导航栏相关方法
function goToMainHome() {
  router.replace('/mainpage').then(() => {
    window.location.reload();
  });
}

function goToPersonalHome() {
  router.push(`/user/${currentUser.id}`);
}

function toggleUserOptionsModal() {
  showUserOptionsModal.value = !showUserOptionsModal.value;
}

function closeUserOptionsModal() {
  showUserOptionsModal.value = false;
}

function logout() {
  currentUser.id = null;
  currentUser.nickname = '默认用户';
  currentUser.avatar = '';
  localStorage.removeItem('user');
  router.push('/login').then(() => {
    window.location.reload();
  });
  closeUserOptionsModal();
}

function goToMessageHome() {
  if (currentUser.id === 4) {
    showLoginModal.value = true;
  } else {
    router.push('/messagehome').then(() => {
      window.location.reload();
    });
  }
}

function goToLogin() {
  showLoginModal.value = false;
  router.push('/login');
}

// 初始化用户信息
onMounted(() => {
  const user = JSON.parse(localStorage.getItem('user'));
  if (user) {
    currentUser.id = user.id;
    currentUser.nickname = user.nickname;
    currentUser.avatar = user.avatar;
  }
});
</script>

<style scoped>
/* 添加顶部导航栏样式 */
.top-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  height: 50px;
}

.left-aligned-header-items {
  display: flex;
  align-items: center;
  flex-grow: 1;
  width: 100%;
}

.header-logo {
  display: flex;
  align-items: center;
  height: 100%;
  margin-left: 24px;
  cursor: pointer;
}

.logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
  margin-right: 60px;
  width: 100px;
  color: #333;
}

.user-profile {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 100px;
}

.user-avatar {
  border-radius: 50%;
  margin-right: 10px;
  width: 30px;
  height: 30px;
  cursor: pointer;
  transition: box-shadow 0.2s;
}
.user-avatar:hover {
  box-shadow: 0 2px 8px rgba(52,152,219,0.15);
}

.username {
  font-weight: bold;
  margin-right: 20px;
  font-size: 15px;
  color: #000;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}

/* 用户选项弹窗样式 */
.user-options-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  z-index: 1000;
}

.user-options-modal {
  position: absolute;
  top: 50px;
  right: 100px;
  width: 150px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.user-option {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-option:hover {
  background-color: #f5f5f5;
}

.option-icon {
  margin-right: 10px;
  font-size: 18px;
}

.option-text {
  font-size: 14px;
  color: #000000;
}

.message-icon {
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: inline-block;
  background-image: url('https://img.icons8.com/sf-regular/48/messaging-.png');
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  text-indent: -9999px;
  transition: filter 0.2s;
}
.message-icon:hover {
  filter: brightness(1.3);
}

/* 原有样式保持不变 */
.activity-detail {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 70px; /* 为固定导航栏留出空间 */
}

.content-wrapper {
  width: 100%;
  max-width: 850px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.activity-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 2px 12px rgba(44, 62, 80, 0.08);
  padding: 36px 48px 28px 48px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 220px;
}

.activity-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding-left: 8px;
  margin-top: 8px;
}

.avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  margin-right: 10px;
}

.nickname {
  font-weight: bold;
  color: #23232b;
}

.activity-main {
  display: flex;
  gap: 24px;
  align-items: flex-start;
  padding-left: 8px;
  padding-right: 8px;
}

.activity-content-block {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
  padding-left: 4px;
}

.activity-content {
  color: #444;
  font-size: 15px;
  text-align: left;
  white-space: pre-wrap;
}

.activity-images {
  display: flex;
  flex-wrap: wrap;
  gap: 18px;
  margin-top: 12px;
  margin-bottom: 0;
  max-width: 100%;
  justify-content: flex-start;
  position: static;
  padding: 0 12px 8px 12px;
  box-sizing: border-box;
}

.activity-img {
  width: 200px;
  height: 200px;
  aspect-ratio: 1 / 1;
  object-fit: cover;
  border-radius: 14px;
  background: #f0f0f0;
  box-shadow: 0 1px 4px rgba(44, 62, 80, 0.08);
  display: block;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

@media (max-width: 900px) {
  .activity-img {
    width: calc((100% - 18px) / 2);
    max-width: calc((100% - 18px) / 2);
    height: calc((100% - 18px) / 2);
  }
}

.activity-img:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(44, 62, 80, 0.15);
}

.activity-topic {
  display: inline-flex;
  align-items: center;
  background: none;
  color: #3498db;
  font-size: 18px;
  font-weight: 600;
  border-radius: 6px;
  padding: 1px 8px 1px 6px;
  margin-bottom: 6px;
  margin-right: 6px;
  cursor: pointer;
  transition: color 0.2s;
  border: none;
  user-select: none;
  max-width: 25%;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.topic-hash {
  font-size: 18px;
  font-weight: 600;
  margin-right: 2px;
  color: #3498db;
}

.topic-text {
  color: inherit;
  font-size: 18px;
  font-weight: 600;
}

:deep(.comment-section) {
  width: 100%;
  max-width: none;
  margin: 0;
}

.login-required-modal .el-dialog__header,
.login-required-modal .el-dialog__footer {
  display: none;
}
.login-required-modal .el-dialog__body {
  background: rgba(0,0,0,0.7);
  color: #fff;
  border-radius: 12px;
  padding: 32px 16px 24px 16px;
}
</style>
